package com.lanju.task;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import com.lanju.common.WxMessageUtil;
import com.lanju.entity.Contract;
import com.lanju.entity.User;
import com.lanju.entity.ZukeContract;
import com.lanju.service.ContractJobService;
import com.lanju.service.UserService;
/**
 * 利用 可重入读写锁  实现查询合同到期定时提醒功能
 * @author zengqd
 * @createTime 2019年9月12日下午5:03:21
 */
@Controller
@Component
public class ContractJob {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ContractJob.class);
	/**
	 * 没有openid的用户
	 */
	List<Map<String,Object>> noOpenIdList = new ArrayList<Map<String,Object>>();//记录没有openid的用户
	
	private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	private int count = 0;
	
	@Autowired
	ContractJobService contractJobService;
	
    @Autowired
    UserService userService;
    
	
	
	@SuppressWarnings("unused")
//	@Scheduled(cron="0 0 12 * * ? ") //间隔5秒执行
//	@Scheduled(cron="0 1/3 * * * ? ") //间隔5秒执行
	public void sendMsg() throws ClientProtocolException, IOException{
		String day30 ;
		String day3 ;
		String day1 ;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar=new GregorianCalendar();
		calendar.add(Calendar.DATE, 1);
		day1 = sdf.format(calendar.getTime());
		calendar.add(Calendar.DATE, 2);
		day3 = sdf.format(calendar.getTime());
		calendar.add(Calendar.DATE, 27);
		day30 = sdf.format(calendar.getTime());
		System.out.println("30天后是:"+day30);
		System.out.println("3天后是:"+day3);
		System.out.println("1天后是:"+day1);
		//管理员
		Map<String,Object> param = new HashMap<>();
		param.put("reviceType", "租客合同到期提醒");
		List<User> userList = userService.getSendMessageUser(param);

		//租客
		List<ZukeContract> list1 = contractJobService.getZuKeContractJob(day1);
		List<ZukeContract> list3 = contractJobService.getZuKeContractJob(day3);
		List<ZukeContract> list30 = contractJobService.getZuKeContractJob(day30);
		eachzkData(list1,userList);
		eachzkData(list3,userList);
		eachzkData(list30,userList);
		//管理员
		Map<String,Object> param1 = new HashMap<>();
		param1.put("reviceType", "业主合同到期提醒");
		List<User> yezhuuserList = userService.getSendMessageUser(param1);
		//业主
		List<Contract> list1_= contractJobService.getContractUserList(day1);
	    List<Contract> list3_= contractJobService.getContractUserList(day3);
		List<Contract> list30_= contractJobService.getContractUserList(day30);
		eachData(list1_,yezhuuserList);
		eachData(list3_,yezhuuserList);
		eachData(list30_,yezhuuserList);
		System.out.println("总共发送："+count+"条信息");
	}
	/**
	 * 业主发送短信
	 * 作者：zengqd
	 * @param list
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public void eachData(List<Contract> list,List<User> userList) throws ClientProtocolException, IOException{		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					lock.readLock().lock();
					if(list != null && list.size()>0){
						for(int i=0;i<list.size();i++){
							Contract c = list.get(i);
							User u = userService.getById(c.getUserId());
							String nickName = c.getUserName();
							String phone = u.getPhone();
							String renter_addr = c.getHouseAddress();
							String openId = u.getOpenId();
							String renter_start_time = sdf.format(c.getContractStartTime()) ;
							String renter_end_time = sdf.format(c.getContractEndTime()) ;
							if(!StringUtils.isEmpty(openId)){//  测试模板  	LBXkmbnO2I6nuBpcUW-aHqujfAshkdqT_-UfBm_EjpM   正式模板 ： R0-_P7OZ_X2XV_wDGByz2k2Ktc1pJJyJFwbr3Jm6TW4
								String data = fillData("R0-_P7OZ_X2XV_wDGByz2k2Ktc1pJJyJFwbr3Jm6TW4", "亲爱的用户，您的合同即将到期", nickName, renter_addr, renter_start_time+"~"+renter_end_time, renter_end_time, openId, "请及时联系蓝居管家退房或续约");
								Map<String,Object> result = WxMessageUtil.contractPayMesgJob(data);	
								count ++;
								for(int m=0 ;m<userList.size();m++){
								User u_ = userList.get(m);
								if(!StringUtils.isEmpty(u_.getOpenId())){
									String data_ =  fillData("R0-_P7OZ_X2XV_wDGByz2k2Ktc1pJJyJFwbr3Jm6TW4", "亲爱的管理员，【"+nickName+"】的合同即将到期", nickName, renter_addr, renter_start_time+"~"+renter_end_time, renter_end_time, userList.get(m).getOpenId(), "客户联系电话是："+ phone);
									Map<String,Object> result1 = WxMessageUtil.contractPayMesgJob(data_);
									count ++;
								}else{
									Map<String,Object> map = new HashMap<String, Object>();
									map.put("nickName", nickName);
									map.put("openId", openId);
									noOpenIdList.add(map);
								}
							}
							}else{
								Map<String,Object> map = new HashMap<String, Object>();
								map.put("nickName", nickName);
								map.put("openId", openId);
								noOpenIdList.add(map);
							}
							
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					lock.readLock().unlock();
				}
	}
	/**
	 * 租客发送短信
	 * 作者：zengqd
	 * @param list
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public void eachzkData(List<ZukeContract> list,List<User> userList) throws ClientProtocolException, IOException{		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			lock.readLock().lock();
			if(list != null && list.size()>0){
				for(int i=0;i<list.size();i++){
					ZukeContract z = list.get(i);
					User u = userService.getById(z.getUserId());
					String phone = u.getPhone();
					String nickName = z.getRenter_name();
					String renter_addr = z.getRenter_addr();
					String openId = u.getOpenId();
					String renter_start_time = sdf.format(z.getRenter_start_time());
					String contract_id = z.getContract_id();
					String renter_end_time =  sdf.format(z.getRenter_end_time());
					if(!StringUtils.isEmpty(openId)){
						String data = fillData("R0-_P7OZ_X2XV_wDGByz2k2Ktc1pJJyJFwbr3Jm6TW4", "亲爱的用户，您的合同即将到期", nickName, renter_addr, renter_start_time+"~"+renter_end_time, renter_end_time, openId, "请及时联系蓝居管家退房或续约");
						Map<String,Object> result = WxMessageUtil.contractPayMesgJob(data);
						count ++;
						for(int n=0 ;n<userList.size();n++){
						User u_ = userList.get(n);
						if(!StringUtils.isEmpty(u_.getOpenId())){
							String data_ =  fillData("R0-_P7OZ_X2XV_wDGByz2k2Ktc1pJJyJFwbr3Jm6TW4", "亲爱的管理员，【"+nickName+"】的合同即将到期", nickName, renter_addr, renter_start_time+"~"+renter_end_time, renter_end_time, userList.get(n).getOpenId(), "客户联系电话是："+ phone);
							Map<String,Object> result1 = WxMessageUtil.contractPayMesgJob(data_);
							count ++;
						}else{
							Map<String,Object> map = new HashMap<String, Object>();
							map.put("nickName", nickName);
							map.put("openId", openId);
							noOpenIdList.add(map);
						}
					}
					}else{
						Map<String,Object> map = new HashMap<String, Object>();
						map.put("nickName", nickName);
						map.put("openId", openId);
						noOpenIdList.add(map);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.readLock().unlock();
		}
		
	}
	/**
	 * 
	 * 作者：zengqd
	 * @param templateId
	 * @param first   标题
	 * @param keyword1 姓名
	 * @param keyword2 房间号
	 * @param keyword3 合同时效
	 * @param keyword4 合同到期时间
	 * @param openid  接收方id
	 * @param remark  备注
	 * @return
	 */
	public String fillData (String templateId,String first,String keyword1,String keyword2,String keyword3,String keyword4,String openid,String remark){
		String data="{\"touser\":\""+openid+"\",\"template_id\":\""+templateId+"\",\"topcolor\":\"#FF0000\", "
				+ "\"data\":{\"first\": { \"value\":\""+first+"\",\"color\":\"#173177\"},"
						+ "\"keyword1\":{\"value\":\""+keyword1+"\",\"color\":\"#173177\" },"
								+ "\"keyword2\": { \"value\":\""+keyword2+"\",\"color\":\"#173177\"},"
										+ "\"keyword3\":{\"value\":\""+keyword3+"\",\"color\":\"#173177\"}, "
										+ "\"keyword4\":{\"value\":\""+keyword4+"\",\"color\":\"#173177\"}, "
												+ "\"remark\":{\"value\":\""+remark+"\",\"color\":\"#173177\"}"
														+ "}}";
		return data;
	}
}
